//
//  AppDelegate+RongCloud.m
//  TreatHeart_Doctor
//
//  Created by Lucas on 2018/6/5.
//  Copyright © 2018年 bluemobi. All rights reserved.
//

/**
 *  推送说明：
 *
 *  我们在知识库里还有推送调试页面加了很多说明，当遇到推送问题时可以去知识库里搜索还有查看推送测试页面的说明。
 *
 *  首先必须设置deviceToken，可以搜索本文件关键字“推送处理”。模拟器是无法获取devicetoken，也就没有推送功能。
 *
 *  当使用"开发／测试环境"的appkey测试推送时，必须用Development的证书打包，并且在后台上传"开发／测试环境"的推送证书，证书必须是development的。
 *  当使用"生产／线上环境"的appkey测试推送时，必须用Distribution的证书打包，并且在后台上传"生产／线上环境"的推送证书，证书必须是distribution的。
 */

#import "AppDelegate+RongCloud.h"
#import "JPUSHService.h"
static NSString * const RongCloudAppKey = @"qf3d5gbjqhbqh";

@implementation AppDelegate (RongCloud)

//登录成功获取到
- (void)addobserverUserLogin {
    [[CacheData cache] addObserver:self forKeyPath:@"userModel" options:NSKeyValueObservingOptionNew context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"userModel"]) {
        NSLog(@"~~~~~%@",USER.token);
        [self connectRongCloudAfterLoginSuccessWithRCToken:USER.token];
        [[RCIM sharedRCIM]refreshUserInfoCache:({
            RCUserInfo *user = [RCUserInfo new];
            user.name = USER.nickName;
            user.portraitUri = USER.headImgUrlPath;
            user;
        }) withUserId:USER.kId];
    }
}
    
#pragma mark - public
- (void)configRongCloudWithOptions:(NSDictionary *)launchOptions
{
    //非debug模式初始化sdk
    [[RCIM sharedRCIM] initWithAppKey:RongCloudAppKey];
    
    //IMKit连接状态的监听器
    [[RCIM sharedRCIM] setConnectionStatusDelegate:self];
    
    //开启用户信息和群组信息的持久化
    [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
    
    //设置接收消息代理
    [RCIM sharedRCIM].receiveMessageDelegate = self;
    
    //开启多端未读状态同步
    [RCIM sharedRCIM].enableSyncReadStatus = YES;
    
    //开启消息撤回功能
    [RCIM sharedRCIM].enableMessageRecall = YES;
    
    //设置Log级别，开发阶段打印详细log
    [RCIMClient sharedRCIMClient].logLevel = RC_Log_Level_Info;
    
    
    //监听 MyAppServer 登录状态并取得融云token
    [self addobserverUserLogin];
    
    
    /**
     * 统计推送打开率1
     */
    [[RCIMClient sharedRCIMClient] recordLaunchOptionsEvent:launchOptions];
    /**
     * 获取融云推送服务扩展字段1
     */
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromLaunchOptions:launchOptions];
    if (pushServiceData) {
        NSLog(@"该启动事件包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"%@", pushServiceData[key]);
        }
    } else {
        NSLog(@"该启动事件不包含来自融云的推送服务");
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didReceiveMessageNotification:)
                                                 name:RCKitDispatchMessageNotification
                                               object:nil];
}



#pragma mark - selector
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    NSNumber *left = [notification.userInfo objectForKey:@"left"];
    if ([RCIMClient sharedRCIMClient].sdkRunningMode == RCSDKRunningMode_Background && 0 == left.integerValue) {
        int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[
                                                                             @(ConversationType_PRIVATE), @(ConversationType_DISCUSSION), @(ConversationType_APPSERVICE),
                                                                             @(ConversationType_PUBLICSERVICE), @(ConversationType_GROUP)
                                                                             ]];
        dispatch_async(dispatch_get_main_queue(),^{
//            [UIApplication sharedApplication].applicationIconBadgeNumber = unreadMsgCount;
        });
    }
}


- (void)connectRongCloudAfterLoginSuccessWithRCToken:(NSString *)rctoken
{
    /* 测试用token */
//    NSString * token = @"u97WKatlJ7kJ5QrvJ/H6uhw/fCenYIl2WqW/hktsZJl0wPHYukfsLlNfdYNOatPXpJSyFO5/x9hYcRpOuQw65A==";
//    rctoken = token;
    /* ---------- */
    
    [[RCIM sharedRCIM] connectWithToken:rctoken success:^(NSString *userId) {
        NSLog(@"融云登陆成功。当前登录的用户ID：%@", userId);
        //连接苹果APNS获取设备token
        dispatch_async(dispatch_get_main_queue(), ^{
        
            [[RCIM sharedRCIM] setUserInfoDataSource:self];
            
            /**
             * 推送处理1/4
             */
            UIApplication * application = [UIApplication sharedApplication];
            if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
                //注册推送, 用于iOS8以及iOS8之后的系统
                UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                        settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)
                                                        categories:nil];
                [application registerUserNotificationSettings:settings];
            } else {
                //注册推送，用于iOS8之前的系统
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                UIRemoteNotificationType myTypes =
                UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
                [application registerForRemoteNotificationTypes:myTypes];
#pragma clang diagnostic pop
            }
            
            
        });
        
    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%ld", (long)status);
    } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
        NSLog(@"token错误");
    }];
}

#pragma mark - RCIMUserInfoDataSource
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *userInfo))completion
{
    NSDictionary *parameters = @{
                                 @"id":userId,
                                 @"memberId":USER.kId,
                                 };
    [API_MANAGER postWithURLString:PersonInformationDetail_Interface parameters:parameters success:^(id model) {
        if ([model[@"result"] intValue] > 0) {
            
            NSDictionary * dataDict = model[@"data"];
            THUserModel * model = [THUserModel yy_modelWithDictionary:dataDict];
            RCUserInfo * userInfo = [[RCUserInfo alloc] init];
            userInfo.userId = userId;
            userInfo.name = model.nickName;
            userInfo.portraitUri = model.headImgUrlPath;
            return completion(userInfo);
        }
    } failure:^(NSError *error) {
    }];
}


    
#pragma mark - RCIMConnectionStatusDelegate
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status
{
    switch (status) {
        case ConnectionStatus_Connected:
        {
            NSLog(@"ConnectionStatus_Connected");
        }
        break;
        
        case ConnectionStatus_Connecting:
        {
            NSLog(@"ConnectionStatus_Connecting");
        }
        break;
        
        case ConnectionStatus_Unconnected:
        {
            NSLog(@"ConnectionStatus_Unconnected");
        }
        break;
        
        case ConnectionStatus_SignUp:
        {
            NSLog(@"ConnectionStatus_SignUp");
        }
        break;
        
        case ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT:
        {
            [MXMainTabBarViewController reSetLoginViewController];
            [YYMB showPlainText:@"此账号在其他设备上登录"];
            NSLog(@"ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT");
        }
        break;
        
        case ConnectionStatus_TOKEN_INCORRECT:
        {
            NSLog(@"ConnectionStatus_TOKEN_INCORRECT");
        }
        break;
        
        default:
        break;
    }
}
   
#pragma mark - UIApplicationDelegate

/**
 * 推送处理2/4
 */
//注册用户通知设置
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    // register to receive notifications
    [application registerForRemoteNotifications];
}

/**
 * 推送处理3/4
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //连接苹果APNS获取设备token
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""]
                        stringByReplacingOccurrencesOfString:@">"
                        withString:@""] stringByReplacingOccurrencesOfString:@" "
                       withString:@""];
    //配置融云获取苹果token
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
    
     [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
#if TARGET_IPHONE_SIMULATOR
    // 模拟器不能使用远程推送
#else
    // 请检查App的APNs的权限设置，更多内容可以参考文档
    // http://www.rongcloud.cn/docs/ios_push.html。
    NSLog(@"获取DeviceToken失败！！！");
    NSLog(@"ERROR：%@", error);
#endif
}


/**
 * 推送处理4/4
 * userInfo内容请参考官网文档
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    /**
     * 统计推送打开率2
     */
    [[RCIMClient sharedRCIMClient] recordRemoteNotificationEvent:userInfo];
    /**
     * 获取融云推送服务扩展字段2
     */
    NSDictionary *pushServiceData = [[RCIMClient sharedRCIMClient] getPushExtraFromRemoteNotification:userInfo];
    if (pushServiceData) {
        NSLog(@"该远程推送包含来自融云的推送服务");
        for (id key in [pushServiceData allKeys]) {
            NSLog(@"key = %@, value = %@", key, pushServiceData[key]);
        }
    } else {
        NSLog(@"该远程推送不包含来自融云的推送服务");
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    /**
     * 统计推送打开率3
     */
    [[RCIMClient sharedRCIMClient] recordLocalNotificationEvent:notification];
    
    //  //震动
    //  AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //  AudioServicesPlaySystemSound(1007);
}

#pragma mark - RCIMConnectionStatusDelegate

- (BOOL)onRCIMCustomLocalNotification:(RCMessage *)message withSenderName:(NSString *)senderName {
    //群组通知不弹本地通知
    if ([message.content isKindOfClass:[RCGroupNotificationMessage class]]) {
        return YES;
    }
    if ([[message.content.class getObjectName] isEqualToString:@"RCJrmf:RpOpendMsg"]) {
        return YES;
    }
    return NO;
}

- (void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left {
    
}

@end
